from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from .utils import OAuthQQ, OAuthQQException
from . import serializers


# GET /oauth/qq/authorization/?next=/ HTTP/1.1" 404 3101
class OAuthAuthorizationCodeView(APIView):
    """获取qq认证code页面"""
    def get(self, request):
        next = request.query_params.get("next")
        oauthqq = OAuthQQ(state=next)
        login_url = oauthqq.get_qq_login_url()
        data = {
            "login_url": login_url
        }
        return Response(data=data)

# "GET /oauth/qq/user/?code=CD37DC0D6578B792FDC087B2405D99E7
class OAuthLoginView(CreateAPIView):
    """QQ登录,绑定视图"""
    serializer_class = serializers.OAuthLoginSerializer

    def get(self, request):
        code = request.query_params.get("code")
        if not code:
            return Response({"message":"缺少参数"})
        oauthqq = OAuthQQ()

        try:
            access_token = oauthqq.get_access_token(code)
            openid = oauthqq.get_openid(access_token)
        except OAuthQQException:
            return ({"message":"QQ服务器返回数据失败"})

        if not openid:
            return Response({"message":"获取openid失败"})
        try:
            oauthqquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            token = oauthqq.generate_qq_user_token(openid)
            return Response({"access_token": token})
        else:
            user = oauthqquser.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            data = {
                "user_id": user.id,
                "username": user.username,
                "token": token
            }
            return Response(data=data)
